<template>
    <view class="store-add pd-v-24 pd-b-72">
      
        <view class="store-add__body overflow-h">
            <u--form
                labelWidth="100"
                labelPosition="left"
                :model="form"
                :rules="rules"
                ref="uForm"
            >
                <view class="border8 pd-l-24 bg-white mr-t-20">
                    <u-form-item
                        label="门店名称"
                        prop="name"
                        borderBottom
                    >
                        <u--input
                            v-model.trim="form.name"
                            border="none"
                            :customStyle="{padding:'12rpx 0'}"
                            placeholder="请输入门店名称"
                        ></u--input>
                    </u-form-item>
                    <u-form-item
                        label="所在地区"
                        prop="birthPlace"
                        borderBottom
                    >
                        <picker mode="region" @change="regionChange">
                            <u-input
                                v-model="form.birthPlace"
                                border="none"
                                clearable
                                readonly
                                placeholder="请输入所在地区"
                            ></u-input>
                        </picker>
                    </u-form-item>
                    
                    <u-form-item
                        label="详细地址"
                        prop="detailedAddress"
                        borderBottom
                    >
                        <u--input
                            v-model.trim="form.detailedAddress"
                            border="none"
                            :customStyle="{padding:'12rpx 0'}"
                            placeholder="请输入详细地址"
                        ></u--input>
                    </u-form-item>
                    
                    <u-form-item
                        label="报修电话"
                        prop="repairPhone"
                        borderBottom
                    >
                        <u--input
                            v-model.trim="form.repairPhone"
                            border="none"
                            :customStyle="{padding:'12rpx 0'}"
                            placeholder="请输入报修电话"
                        ></u--input>
                    </u-form-item>
                </view>


                <view class="border8 pd-v-24 pd-h-24 bg-white mr-t-20">
                    <view class="flex flex-center">
                        <view class="font28 lh-40 color-default bold">
                            门店图片
                        </view>
                        <view class="flex-1 font28 lh-28 color-note">
                            （最多可上传6张）
                        </view>
                    </view>
                    <u-form-item prop="image">
                        <view class="mr-t-16 flex flex-wrap">
                            <template v-if="form.image.length">
                                <view class="flex flex-center flex-j-center border-default border8 position-r mr-r-10 mr-t-10" style="width: 200rpx;height: 200rpx;" v-for="(item,index) in form.image" :key="'hhh'+index">
                                    <image
                                        :src="getFileUrl(item)"
                                        style="width:100%;height:100%;"
                                        mode="aspectFit"
                                        @click="previewImage(item)"
                                    ></image>
                                    
                                    <view class="image-close-btn pd-v-10 pd-h-10 position-a" @click="removeImage(index)">
                                        <view class="bg-white border100">
                                            <u-icon name="close-circle-fill" size="18" color="#4c4c4c"></u-icon>
                                        </view>
                                        
                                    </view>
                                </view>
                            </template>
                            <view class="flex flex-center flex-j-center border-default border8 mr-r-10 mr-t-10" style="width: 200rpx;height: 200rpx;" @click="chooseImage" v-if="form.image.length < 6">
                                选择图片
                            </view>
                            
                        </view>
                    </u-form-item>
                      
                </view>

                <view class="border8 pd-v-24 bg-white mr-t-20">
                    <view class="flex flex-center">
                        <view class="flex-1">
                            <u-form-item
                                label="电费"
                                prop="chargeFee"
                            >
                                <u--input
                                    v-model.trim="form.chargeFee"
                                    border="none"
                                    :customStyle="{padding:'12rpx 0'}"
                                    placeholder="请输入电费"
                                ></u--input>
                            </u-form-item>
                        </view>
                        
                        <view class="font28 lh-40 color-default bold">
                            元/度
                        </view>
                    </view>
                      
                      
                </view>

                <view class="border8 pd-v-24 pd-h-24 bg-white mr-t-20">
                    <view class=" font28 lh-28 color-default">
                        服务费
                    </view>
                      
                    <view class="flex mr-t-10 position-r" v-for="(item,index) in form.serviceChargeList" :key="'in'+index">
                        <view class="flex-1">
                            <u-form-item
                                :prop="`serviceChargeList.${index}.startPower`"
                            >
                                <u--input
                                    v-model.trim="item.startPower"
                                    border="none"
                                    disabled
                                    type="text"
                                    :customStyle="{padding:'8rpx 8rpx',background:'#f1f1f1'}"
                                    placeholder="功率"
                                    fontSize="24rpx"
                                    color="#C0C4CC"
                                    inputAlign="center"
                                ></u--input>
                            </u-form-item>
                        </view>
                        <text class="font24 lh-40 color-default pd-v-8 mr-t-32">
                            瓦-
                        </text>
                          
                        <view class="flex-1">
                            <u-form-item
                                :prop="`serviceChargeList.${index}.endPower`"
                                @click="chooseEndPower(item)"
                            >
                                <u--input
                                    v-model.trim="item.endPower"
                                    border="none"
                                    readonly
                                    :customStyle="{padding:'8rpx 8rpx',background:'#F5F7FA'}"
                                    placeholder="功率"
                                    fontSize="24rpx"
                                    color="f3f3f3"
                                    type="text"
                                    inputAlign="center"
                                ></u--input>
                            </u-form-item>
                        </view>
                        <text class="font24 lh-40 color-default pd-v-8 mr-t-32">
                            瓦
                        </text>
                        <view class="flex-1 mr-l-40">
                            <u-form-item
                                 :prop="`serviceChargeList.${index}.price`"
                            >
                                <u--input
                                    v-model.trim="item.price"
                                    border="none"
                                    :customStyle="{padding:'8rpx 8rpx',background:'#F5F7FA',color:'#C0C4CC'}"
                                    placeholder="价格(元小时)"
                                    fontSize="24rpx"
                                    color="f3f3f3"
                                    type="digit"
                                    inputAlign="center"
                                ></u--input>
                            </u-form-item>
                        </view>

                        <view class="close-btn pd-v-10 pd-h-10 position-a" v-if="index>0" @click="remove(index)">
                            <u-icon name="close-circle-fill" size="18" color="#4c4c4c"></u-icon>
                        </view>
                          
                    </view>

                    <view class="mr-t-30 pd-v-24 flex flex-center flex-j-center">
                        <u-button plain :customStyle="{height:'76rpx',width:'600rpx',borderStyle:'dashed'}" color="#999390"  text="新增 +" @click="add"></u-button>
                    </view>
                      
                </view>


                <view class="mr-t-40 flex flex-center flex-j-center">
                    <u-button shape="circle"  :customStyle="{height:'88rpx',width:'600rpx'}" color="#35BE65"  text="确认" @click="submit"></u-button>
                </view>
                  
            </u--form>
        </view>
          
        <u-picker :show="show" :columns="getRange(activeItem?.startPower)" @close="close" @cancel="cancel" @confirm="confirm"></u-picker>
    </view>
</template>

<script setup>
import { useStore } from '@/store/index.js';
import { ref, reactive, onMounted, watch,defineProps } from 'vue';
import { onLoad, onReady, onShow } from '@dcloudio/uni-app';

import { storeAdd, storeUpdate,storeQueryById } from '@/api/proxy.js'
import {upload} from '@/api/index/index'
const FormData = require('../../../static/formdata.js')
import { fileUrl } from '@/utils/index.js'

const props = defineProps({
    storeId: {
        type: String,
        default: ''
    }
});
const store = useStore();
const form = ref({
    name: '',
    birthPlace: '',
    detailedAddress:'',
    repairPhone:'',
    image:[],
    chargeFee:'',
    serviceChargeList:[{
        startPower:'0',
        endPower:'',
        price:''
    }]
});
const uForm = ref(null);
const rules = ref({
    name: [
        {
            required: true,
            message: '请输入店铺名称',
            trigger: ['blur','change']
        }
    ],
    birthPlace: [
        {
            required: true,
            message: '请选择区域',
            trigger: ['blur','change']
        }
    ],
    detailedAddress: [
        {
            required: true,
            message: '请输入详细地址',
            trigger: ['blur','change']
        }
    ],
    repairPhone: [
        {
            message: '请输入手机号',
            trigger: ['blur','change'],
            validator: (rule, value, callback) => {
                let phoneReg = /^1[3-9]\d{9}$/;
                if (!value) {
                    callback('请输入手机号');
                    return false;
                } else if(!phoneReg.test(value)){
                    callback('请输入正确的手机号');
                    return false;
                } else {
                    callback();
                }
            }
        }
    ],
    chargeFee: [
        {
            required: true,
            message: '请输入电费',
            trigger: ['blur','change'],
            transform: (value) => {
                return String(value);
            }
        }
    ],
    serviceChargeList: [
        {
            required: true,
            message: '请输入服务费',
            trigger: ['blur','change']
        }
    ],
    image: [
        {
            message: '请上传店铺图片',
            trigger: ['blur','change'],
            validator: (rule, value, callback) => {
                if (value.length === 0) {
                    callback('请上传店铺图片');
                    return false;
                } else {
                    callback();
                }
            }
        }
    ],
    startPower: [
        {
            message: '请输入功率',
            trigger: ['blur','change']
        }
    ],
    endPower: [
        {
            required: true,
            message: '请输入功率',
            trigger: ['blur','change']
        }
    ],
    price: [
        {
            required: true,
            message: '请输入价格',
            trigger: ['blur','change']
        }
    ]
})
const show = ref(false);
const activeItem = ref({});

watch(form.value.serviceChargeList,(newVal,oldVal) => {
    // console.log(JSON.parse(JSON.stringify(oldVal)))
    // console.log(JSON.parse(JSON.stringify(newVal)))

    refreshStartPower();
},{ deep: true })

onReady(() => {
    setRules()
})

onShow(() => {
    
})

onLoad(() => {
    if(props.storeId) {
        getStoreQueryById();
    }
})

const getStoreQueryById = () => {
    storeQueryById({storeId:props.storeId}).then(res => {
        console.log(res,'resssssss')
        if(res.code == 200) {
            res.data.image = res.data.image.split(',')
            res.data.birthPlace = res.data.birthPlace.join(' ')
            form.value = res.data
        }
    })
}

const removeImage = (index) => {
    form.value.image.splice(index,1);
    setRules()
    refreshStartPower()
}

const getFileUrl = (url) => {
    return fileUrl(url)
}

const close = () => {
    show.value = false;
}

const cancel = () => {
    show.value = false;
}

const confirm = (e) => {
    let index = form.value.serviceChargeList.findIndex(item => item == activeItem.value);
    activeItem.value.endPower = String(e.value[0]);
    show.value = false;
    refreshStartPower()
}

const chooseEndPower = (item) => {
    activeItem.value = item;
    show.value = true;
}

const getRange = (start) => {
    let rangeList = [];
    for (let i = 0; i <= 3500; i+=50) {
        if(start || start == 0) {
            if(i > start) {
            rangeList.push(i);
            }
        } else {
            rangeList.push(i);
        }
    
    }
    console.log(rangeList)
    return [rangeList];
}

const refreshStartPower = () => {
    form.value.serviceChargeList.forEach((item, index) => {
        if(index == 0) {
            item.startPower = '0';
        } else {
            item.startPower = form.value.serviceChargeList[index - 1].endPower;
        }

    })
}

const regionChange = (e) => {
    form.value.birthPlace = e.detail.value.join(' ')
    uForm.value.validateField('birthPlace')
}

const setRules = () => {
    uForm.value.setRules(rules.value);
    form.value.serviceChargeList.forEach((ele, index) => {
        rules.value[`serviceChargeList.${index}.startPower`] = {
            message: '请输入功率',
            trigger: ['blur','change'],
            transform: (value) => {
                return String(value);
            }
        }
        rules.value[`serviceChargeList.${index}.endPower`] = {
            required: true,
            message: '请输入功率',
            trigger: ['blur','change'],
            transform: (value) => {
                return String(value);
            }
        }
        rules.value[`serviceChargeList.${index}.price`] = {
            required: true,
            message: '请输入价格',
            trigger: ['blur','change'],
            transform: (value) => {
                return String(value);
            }
        }
    })
}


const chooseImage = () => {
    if(form.value.image.length >= 6) {
        uni.showToast({
            title: '最多上传6张图片',
            icon: 'none'
        })
        return;
    }
    uni.chooseImage({
        count: 1, //默认9
        sizeType: ['original'], //可以指定是原图还是压缩图，默认二者都有
        sourceType: ['album','camera '], //从相册选择
        success: function (res) {
            console.log(res.tempFilePaths);
            const tempFilePaths = res.tempFilePaths[0];
            console.log(FormData)
            let formData = new FormData.default();
        
            formData.append("name", "value");      // value 表单值
            formData.appendFile("file", tempFilePaths); // filepath 文件路径
            
            // formData.getData() => { 
            //   buffer:<ArrayBuffer>[], // buffer	表单数据的ArrayBuffer对象 
            //   contentType: string,    // http请求Content-Type头部内容
            // } 
            const data = formData.getData();
            console.log(data)
            upload(data).then(res => {
                console.log(res)
                if(res.code == 200) {
                    form.value.image.push(res.fileName)
                }else {
                              uni.showToast({
                                  title: res.msg,
                                  icon: 'none'
                              })
                          }
            })
        }
    })
}


const add = () => {
    form.value.serviceChargeList.push({
        startPower:'0',
        endPower:'',
        price:''
    })
    
    
    setRules()
    refreshStartPower()
}


const submit = () => {
    console.log(form.value.serviceChargeList)
    uForm.value.validate().then(res => {
        let params = {
            name: form.value.name,
            detailedAddress: form.value.detailedAddress,
            birthPlace: form.value.birthPlace.split(' '),
            image: form.value.image.join(','),
            serviceChargeList: form.value.serviceChargeList,
            chargeFee:form.value.chargeFee,
            repairPhone:form.value.repairPhone

        }


        console.log(params,'params')
        if(props.storeId) {
            params.id = props.storeId;
            storeUpdate(params).then(res => {
                if(res.code == 200) {
                    uni.showToast({
                        title: '修改成功',
                        icon: 'none'
                    })
                    setTimeout(() => {
                        uni.navigateBack({
                            delta: 1
                        })
                    },1500)
                } else {
                    uni.showToast({
                        title: res.msg,
                        icon: 'none'
                    })
                }
            })
        } else {
            
            storeAdd(params).then(res => {
                if(res.code == 200) {
                    uni.showToast({
                        title: '添加成功',
                        icon: 'none'
                    })
                    setTimeout(() => {
                        uni.navigateBack({
                            delta: 1
                        })
                    },1500)
                } else {
                    uni.showToast({
                        title: res.msg,
                        icon: 'none'
                    })
                }
            })
        }
    }).catch(err => {
        console.log(err,'eeeeeeeeeeeeeeeee')
    })
}


const remove = (index) => {
    form.value.serviceChargeList.splice(index,1)
}

const previewImage = (item) => {
    uni.previewImage({
        urls: [getFileUrl(item)]
    })
}

</script>

<style scoped lang="scss">
.store-add {
    background: #F7F7F7;
    min-height:100vh;
    
    ::v-deep .u-form-item__body__right__message {
        margin-left:0!important;
    }

    .close-btn {
        right:-20rpx;
        top:0;
        z-index: 9999;
    }

    .image-close-btn {
        right: -20rpx;
        top: -20rpx;
        z-index: 9999;
    }
}
</style>
